package com.xjw.coreutil.common;

import cn.hutool.core.codec.Base64;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import cn.hutool.setting.dialect.Props;
import com.alibaba.fastjson2.TypeReference;
import com.xjw.coreutil.cache.CacheUtil;
import com.xjw.coreutil.http.JsonUtil;

import java.io.File;

/**
 * @author xwx1052336
 * @since 2021/9/15
 */
public class PropUtil {

    private static Log LOG = LogFactory.get();

    /**
     * 保存初始化数据
     */
    public static final String INITDATA = "config/init.properties";

    /**
     * 保存用户数据
     */
    public static final String USERDATA = "config/userData.properties";

    private File config;

    private Props props;

    private PropUtil() { }

    public static PropUtil getInstance(String path) {
        return getInstance(path, false);
    }

    public static PropUtil getInstance(String path, boolean isAutoLoad) {
        PropUtil propUtil = CacheUtil.get(path);
        if (propUtil == null) {
            propUtil = new PropUtil();
            propUtil.config = FileUtil.newFile(path);
            propUtil.props = new Props(propUtil.config);
            propUtil.props.autoLoad(isAutoLoad);
            CacheUtil.put(path, propUtil);
        }
        return propUtil;
    }

    public <T> T getValue(String key){
        return CommonUtil.cast(JsonUtil.parseObject(props.getStr(key), new TypeReference<T>(){}));
    }

    public String getStr(String key) {
        return props.getStr(key);
    }

    public String getChStr(String key) {
        return Base64.decodeStr(props.getStr(key));
    }

    public boolean getBool(String key) {
        return props.getBool(key, false);
    }

    public long getLong(String key) {
        return props.getLong(key);
    }

    public void putJson(String key, Object value) {
        setProperty(key, JsonUtil.objectToString(value));
        store();
    }

    public void setProperty(String key, Object value) {
        if(value != null){
            props.setProperty(key,value);
        }
    }

    public void setChStr(String key, String value) {
        if (StringUtil.isNotEmpty(value)) {
            props.setProperty(key, Base64.encode(value));
        }
    }

    public void store(String path){
        props.store(path);
    }

    public void store(){
        props.store(config.getAbsolutePath());
    }

    public String getPath(){
        return config.getAbsolutePath();
    }

}
